using GroupSix.Application.Dtos;
using GroupSix.Application.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace GroupSix.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
    private readonly FileService _fileService;
    private readonly ILogger<FileController> _logger;

    public FileController(FileService fileService, ILogger<FileController> logger)
    {
        _fileService = fileService;
        _logger = logger;
    }

    /// <summary>
    /// 通用文件上传
    /// </summary>
    /// <param name="file">上传的文件</param>
    /// <param name="fileType">文件类型</param>
    /// <param name="businessModule">业务模块</param>
    /// <param name="businessId">业务ID</param>
    /// <param name="description">文件描述</param>
    /// <returns>文件信息</returns>
    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile([FromForm] IFormFile file, [FromForm] string fileType, [FromForm] string businessModule, [FromForm] Guid? businessId, [FromForm] string? description)
    {
        try
        {
            if (file == null)
            {
                return BadRequest(new { success = false, message = "请选择要上传的文件" });
            }

            var request = new FileUploadRequestDto
            {
                FileType = fileType,
                BusinessModule = businessModule,
                BusinessId = businessId,
                Description = description
            };

            var result = await _fileService.UploadFileAsync(file, request);
            return Ok(new { success = true, data = result, message = "文件上传成功" });
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("文件上传验证失败: {Message}", ex.Message);
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件上传失败");
            return StatusCode(500, new { success = false, message = "文件上传失败，请稍后重试" });
        }
    }

    /// <summary>
    /// 用户头像上传
    /// </summary>
    /// <param name="file">头像文件</param>
    /// <param name="userId">用户ID</param>
    /// <returns>文件信息</returns>
    [HttpPost("avatar")]
    public async Task<IActionResult> UploadAvatar([FromForm] IFormFile file, [FromForm] Guid userId)
    {
        try
        {
            if (file == null)
            {
                return BadRequest(new { success = false, message = "请选择要上传的头像文件" });
            }

            var request = new FileUploadRequestDto
            {
                FileType = "avatar",
                BusinessModule = "user",
                BusinessId = userId,
                Description = "用户头像"
            };

            var result = await _fileService.UploadFileAsync(file, request);
            return Ok(new { success = true, data = result, message = "头像上传成功" });
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("头像上传验证失败: {Message}", ex.Message);
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "头像上传失败");
            return StatusCode(500, new { success = false, message = "头像上传失败，请稍后重试" });
        }
    }

    /// <summary>
    /// 获取文件信息
    /// </summary>
    /// <param name="fileId">文件ID</param>
    /// <returns>文件信息</returns>
    [HttpGet("{fileId}")]
    public IActionResult GetFileInfo(Guid fileId)
    {
        try
        {
            var fileInfo = _fileService.GetFileInfo(fileId);
            return Ok(new { success = true, data = fileInfo, message = "获取文件信息成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文件信息失败: {FileId}", fileId);
            return StatusCode(500, new { success = false, message = "获取文件信息失败" });
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fileId">文件ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{fileId}")]
    public IActionResult DeleteFile(Guid fileId)
    {
        try
        {
            var result = _fileService.DeleteFile(fileId);
            if (result)
            {
                return Ok(new { success = true, message = "文件删除成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文件删除失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除文件失败: {FileId}", fileId);
            return StatusCode(500, new { success = false, message = "删除文件失败" });
        }
    }
} 